<?php
// 多表联合查询多条  带分组
function  join_group($table,$field,$join,$where = null,$order = null,$limit = null,$group){
    $result = M($table)->field($field)->join($join)->where($where)->order($order)->limit($limit)->group($group)->select();
    if($result){ return $result;}else{return false;}
}
//日志记录
function logs($co){
    $content = "管理员：".$_SESSION['admin']['numbers']." 于 ".date("Y-m-d H:i:s",time())."{$co}的信息";
    $log     = ins("logs",array("content"=>$content,"admin_id"=>$_SESSION['admin']['id'],"create_at"=>time()));
}
function zhuan($user_id){
    $zhuan = sels("zhuan","zhuan_id","user_id = {$user_id}");
    foreach ($zhuan as $k=>$v){
        $id[] = $v['zhuan_id'];
    }
    $ids                = implode(",",$id);
    $zhuan_user         = sels("users","id,nickname,headimgurl,name,phone,create_at",array("id"=>array("in",$ids)));
    return $zhuan_user;
}
//查询一条
function sel($table,$field,$where=null,$order=null,$limit=null){
    $result = M($table)->field($field)->where($where)->order($order)->limit($limit)->find();
    if($result){ return $result;}else{return false;}
}
//多表联合查询,查一条
function joins($table,$filed,$join,$where = null){
    $list      = M($table)->field($filed)->join($join)->where($where)->find();//获取数据
    return $list;
}

//修改一条信息
function up_one($table,$where,$data){
    $result = M($table)->where($where)->save($data);
    if($result){ return $result;}else{return false;}
}

//添加一条数据
function ins($table,$data){
    $result = M($table)->add($data);
    if($result){ return $result;}else{return false;}
}

//删除一条
function del($table,$id){
    if(is_array($id)){
        $result = M($table)->where($id)->delete();
    }else{
        $result = M($table)->where(array("id"=>$id))->delete();
    }
    if($result){ return $result;}else{return false;}
}
//删除多条
function dels($table,$id){
    if(is_array($id)){
        $result = M($table)->where($id)->delete();
    }else{
        $result = M($table)->where(array("id"=>array("in",$id)))->delete();
    }
    if($result){ return $result;}else{return false;}
}

//查询多条语句/模糊查询查询多条语句
function sels($table,$field,$where = null,$order = null,$limit = null){
    $result = M($table)->field($field)->where($where)->order($order)->limit($limit)->select();
    if($result){ return $result;}else{return false;}
}

// 多表联合查询多条
function  joinss($table,$field,$join,$where = null,$order = null,$limit = null){
    $result = M($table)->field($field)->join($join)->where($where)->order($order)->limit($limit)->select();
    if($result){ return $result;}else{return false;}
}


//分页
function currpage($table,$where = null,$pagesize,$currpage,$order){
    $totalrows = M($table)->where($where)->count();;//总数
    $totalpage = ceil($totalrows/$pagesize);
    $offset    = ($currpage-1)*$pagesize;//偏移量
    $list      = M($table)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
    //判断该页有没有数据 如果没有则显示前一页数据
    if(!$list && $currpage>2){
        $offset    = ($currpage-2)*$pagesize;//偏移量
        $list      = M($table)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
        $currpage  = $currpage-1;
    }
    $arr       = array("totalpage"=>$totalpage,"list"=>$list,"currpage"=>$currpage);
    return $arr;
}
//分页+联合查询
function currpages($table,$filed,$join,$where = null,$order,$pagesize,$currpage){
   // $wh = substr($where,2);
    $totalrows = M($table)->field($filed)->join($join)->where($where)->count();//总数
    $totalpage = ceil($totalrows/$pagesize);
    $offset    = ($currpage-1)*$pagesize;//偏移量
    $list      = M($table)->field($filed)->join($join)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
    //判断该页有没有数据 如果没有则显示前一页数据
    if(!$list && $currpage>2){
        $offset    = ($currpage-2)*$pagesize;//偏移量
        $list      = M($table)->field($filed)->join($join)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
        $currpage  = $currpage-1;
    }
    $arr       = array("totalpage"=>$totalpage,"list"=>$list,"currpage"=>$currpage);
    return $arr;
}
//分页+联合查询
function currpages_group($table,$filed,$join,$where = null,$order,$pagesize,$currpage,$group){
    // $wh = substr($where,2);
    $totalrows = M($table)->field($filed)->join($join)->where($where)->count();//总数
    $totalpage = ceil($totalrows/$pagesize);
    $offset    = ($currpage-1)*$pagesize;//偏移量
    $list      = M($table)->field($filed)->join($join)->where($where)->order($order)->limit("{$offset},{$pagesize}")->group($group)->select();//获取数据
    //判断该页有没有数据 如果没有则显示前一页数据
    if(!$list && $currpage>2){
        $offset    = ($currpage-2)*$pagesize;//偏移量
        $list      = M($table)->field($filed)->join($join)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
        $currpage  = $currpage-1;
    }
    $arr       = array("totalpage"=>$totalpage,"list"=>$list,"currpage"=>$currpage);
    return $arr;
}
//有父级子集的嵌套显示
function overlay($table,$where,$order,$pagesize,$currpage){
    $totalrows = M($table)->where($where)->count();;//总数
    $totalpage = ceil($totalrows/$pagesize);
    $offset    = ($currpage-1)*$pagesize;//偏移量
    $list      = M($table)->where($where)->order($order)->limit("{$offset},{$pagesize}")->select();//获取数据
    foreach ($list as $k=>$v){
        $list[$k]['info'] = sels($table,array("pid"=>$v['id']));
    }
    $arr       = array("totalpage"=>$totalpage,"list"=>$list);
    return $arr;
}

/*
 * 数据批量导入导出
 */
function exportExcel($expTitle,$expCellName,$expTableData){
    $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    $fileName = $_SESSION['account'].date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);
    $dataNum = count($expTableData);
    Vendor('Classes.PHPExcel');
    $objPHPExcel = new \PHPExcel();
    $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

    $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
    for($i=0;$i<$cellNum;$i++){
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
    }
    for($i=0;$i<$dataNum;$i++){
        for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
        }
    }
    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    //$objWriter = \PHPExcel_IOFactory::
    $objWriter->save('php://output');
    exit;
}
/**
 *
 * 导出Excel
 */
function expUser(){//导出Excel
    $xlsName  = "User";
    $xlsCell  = array(
        array('id','账号序列'),
        array('name','备注')
    );
    $xlsModel = M('test');

    $xlsData  = $xlsModel->Field('id,name')->select();
    /* foreach ($xlsData as $k => $v)
     {
         $xlsData[$k]['sex']=$v['sex']==1?'男':'女';
     }*/
    $this->exportExcel($xlsName,$xlsCell,$xlsData);

}
/**
 *
 * 导入Excel
 */
function impUser(){
    if (!empty($_FILES)) {
        import("@.ORG.UploadFile");
        $upload = new \Think\Upload();
        //$upload->maxSize   = 8388608;
        $upload->exts      = array('xlsx','xls');
        $upload->rootPath  = 'Data/';
        $upload->savePath  = "excel/";
        //$upload->autoSub   = true;
        //$upload->subName   = array('date','Y-m');
        $info   =   $upload->upload();
        Vendor('Classes.PHPExcel');
        $file_name = "./Data/".$info['import']['savepath'].$info['import']['savename'];
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel = $objReader->load($file_name,$encode='utf-8');
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数
        for($i=3;$i<=$highestRow;$i++)
        {
            $data['name'] = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
            M('test')->add($data);
        }
        $this->success('导入成功！');
    }else
    {
        $this->error("请选择上传的文件");
    }
}
//地址栏加密************************************************
/**
 * 系统加密方法
 * @param string $data 要加密的字符串
 * @param string $key  加密钥
 * @param int $expire  过期时间 单位 秒
 * return string
 */
function think_base_encode($data, $key = 'bozhi', $expire = 0) {
    $key  = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data = base64_encode($data);
    $x    = 0;
    $len  = strlen($data);
    $l    = strlen($key);
    $char = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    $str = sprintf('%010d', $expire ? $expire + time():0);
    for ($i = 0; $i < $len; $i++) {
        $str .= chr(ord(substr($data, $i, 1)) + (ord(substr($char, $i, 1)))%256);
    }
    return str_replace(array('+','/','='),array('-','_',''),base64_encode($str));
}
/**
 * 系统解方法
 * @param  string $data 要解的字符串 （必须是think_encrypt方法加密的字符串）
 * @param  string $key  加密密钥
 * return string
 */
function think_base_decode($data, $key = 'bozhi'){
    $key    = md5(empty($key) ? C('DATA_AUTH_KEY') : $key);
    $data   = str_replace(array('-','_'),array('+','/'),$data);
    $mod4   = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    $data   = base64_decode($data);
    $expire = substr($data,0,10);
    $data   = substr($data,10);
    if($expire > 0 && $expire < time()) {
        return '';
    }
    $x      = 0;
    $len    = strlen($data);
    $l      = strlen($key);
    $char   = $str = '';
    for ($i = 0; $i < $len; $i++) {
        if ($x == $l) $x = 0;
        $char .= substr($key, $x, 1);
        $x++;
    }
    for ($i = 0; $i < $len; $i++) {
        if (ord(substr($data, $i, 1))<ord(substr($char, $i, 1))) {
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
        }else{
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
        }
    }
    return base64_decode($str);
}
//递归实现无限极分类
function get_attr($a,$pid){
    $tree = array();                                //每次都声明一个新数组用来放子元素
    foreach($a as $v){
        if($v['pid'] == $pid){                      //匹配子记录
            $v['children'] = get_attr($a,$v['id']); //递归获取子记录
            if($v['children'] == null){
                unset($v['children']);             //如果子元素为空则unset()进行删除，说明已经到该分支的最后一个元素了（可选）
            }
            $tree[] = $v;                           //将记录存入新数组
        }
    }
    return $tree;                                  //返回新数组
}
